package operator;

import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.operators.AbstractStreamOperator;
import org.apache.flink.streaming.api.operators.OneInputStreamOperator;
import org.apache.flink.streaming.api.operators.StreamFilter;
import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;

/**
 * Flink的Filter 底层使用
 */
public class FilterDemo2 {

    public static void main(String[] args) throws Exception {
        // Flink配置
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 80);
        // 创建带Webui的Flink本地执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(conf);
        // 使用socket创建DataStream
        DataStreamSource<String> data = env.socketTextStream("192.168.56.10", 8888);


        // 调用transform
        SingleOutputStreamOperator<Integer> filtered = data.transform("MyMapFilter", TypeInformation.of(Integer.class), new MyStreamFilter());

        // sink
        filtered.print();

        env.execute("map operator");
    }

    // 创建一个用于filter操作的StreamFilter类 对数据流进行处理
    public static class MyStreamFilter extends AbstractStreamOperator<Integer> implements OneInputStreamOperator<String, Integer> {

        @Override
        public void processElement(StreamRecord<String> element) throws Exception {
            try {
                Integer i = Integer.parseInt(element.getValue());
                if (i % 2 == 0) {
                    output.collect(element.replace(i));
                }
            } catch (NumberFormatException e) {

            }
        }
    }

}
